import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:get/state_manager.dart';

import '../../bean/bean_study_data.dart';
import '../../utils/navigator_utils.dart';
import 'controller/study_data_controller.dart';
import 'main_study_data_details_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class StudyDataPage extends StatefulWidget {
  const StudyDataPage({Key key}) : super(key: key);

  @override
  _StudyDataPageState createState() => _StudyDataPageState();
}

///当前页面被装载在[PageView]中，使用KeepAlive使用页面保持状态
class _StudyDataPageState extends State<StudyDataPage>
    with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
    Get.put(MyStudyDataController());
    Future.delayed(Duration.zero, () {
      Get.find<MyStudyDataController>().onPullRefresh();
    });
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: GetBuilder(
        id: "Category",
        builder: (MyStudyDataController controller) {
          return buildManiWidget(controller);
        },
      ),
    );
  }

  //滑动控制器
  final ScrollController _scrollController = ScrollController();
  int _firstIndex = 0;
  int _lastIndex = 0;
  int _currentIndex = 0;

  buildManiWidget(MyStudyDataController controller) {
    if (controller.isLoading) {
      return LoadingWidget();
    }
    List<MaterialCategoryBean> studyDataList = controller.materialCategoryList;
    if (studyDataList.length == 0) {
      return NoDataWidget(
        clickCallBack: () {
          Get.find<MyStudyDataController>().onClickItemRefresh(_currentIndex);
        },
      );
    }
    return Column(
      children: [
        Container(
          height: 38,
          child: ListView.custom(
            padding: const EdgeInsets.only(left: 5, right: 5),
            //控制器
            controller: _scrollController,
            //缓存空间
            cacheExtent: 0.0,
            scrollDirection: Axis.horizontal,
            //自定义代理
            childrenDelegate: CustomScrollDelegate(
              (BuildContext context, int index) {
                MaterialCategoryBean bean = studyDataList[index];
                //ListView的子条目
                return Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [buildItemContainer(index, bean)],
                );
              },
              //条目个数
              itemCount: studyDataList.length,
              //滑动回调
              scrollCallBack: (int firstIndex, int lastIndex) {
                print(
                    "firstIndex $firstIndex lastIndex $lastIndex _currentIndex $_currentIndex");
                _firstIndex = firstIndex;
                _lastIndex = lastIndex;
              },
            ),
          ),
        ),
        Expanded(
          child: GetBuilder(
            id: "MaterialList",
            builder: (MyStudyDataController controller) {
              return buildItemListWidget(controller);
            },
          ),
        )
      ],
    );
  }

  Container buildItemContainer(int index, MaterialCategoryBean bean) {
    return Container(
        margin: EdgeInsets.only(left: 4, right: 4),
        height: 28,
        child: ElevatedButton(
            style: ButtonStyle(
              elevation: MaterialStateProperty.all(
                index == _currentIndex ? 10 : 0,
              ),
              backgroundColor: MaterialStateProperty.resolveWith(
                (states) {
                  if (index == _currentIndex) {
                    return Colors.orange;
                  }
                  //默认状态使用灰色
                  return Colors.grey;
                },
              ),
            ),
            onPressed: () {
              _currentIndex = index;
              //计算当前屏幕中间显示的Item的索引
              double mid = (_firstIndex + _lastIndex) *1.0/ 2;
              //获取当前ListView滑动的距离
              double offset = _scrollController.offset;
              if (index*1.0 > mid) {
                //向左
                _scrollController.animateTo(offset + 100,
                    duration: Duration(milliseconds: 400),
                    curve: Curves.easeInSine);
                Get.find<MyStudyDataController>().updateIndex(_currentIndex);
                return;
              }
              //当前显示的是第一个Item
              if (_firstIndex == 0) {
                //完全显示的第一个 不滑动
                if (offset == 0) {
                  Get.find<MyStudyDataController>().updateIndex(_currentIndex);
                  return;
                }
                //未完全显示第一个 滑动到顶部
                _scrollController.animateTo(0,
                    duration: Duration(milliseconds: 400),
                    curve: Curves.easeInSine);
                Get.find<MyStudyDataController>().updateIndex(_currentIndex);
                return;
              }
              //向右
              _scrollController.animateTo(offset - 100,
                  duration: Duration(milliseconds: 400),
                  curve: Curves.easeInSine);
              Get.find<MyStudyDataController>().updateIndex(_currentIndex);
            },
            child: Text("${bean.categoryName}")));
  }

  buildItemListWidget(MyStudyDataController controller) {
    if (controller.isListLoading) {
      return LoadingWidget();
    }

    List<StudyDataBean> studyDataList = controller.studyDataBeanList;
    if (studyDataList.length == 0) {
      return NoDataWidget(
        clickCallBack: () {
          Get.find<MyStudyDataController>().onClickItemRefresh(_currentIndex);
        },
      );
    }

    return buildListWidget(controller.studyDataBeanList);
  }

  buildListWidget(List<StudyDataBean> studyDataList) {
    return RefreshIndicator(
      onRefresh: () async {
        return Get.find<MyStudyDataController>()
            .onClickItemRefresh(_currentIndex);
      },
      child: ListView.builder(
        itemCount: studyDataList.length,
        itemBuilder: (BuildContext context, int index) {
          StudyDataBean item = studyDataList[index];
          bool isShowTitle = true;
          bool isShowBottomTitle = true;
          //0 PPT；1 Word；2 Excel；3 视频；4 PDF；5 Text文本；6图片
          int type = item.videoTypes;
          String typeStr = "-";
          Color textColor = Colors.grey;
          if (type == 0) {
            typeStr = "PPT";
            textColor = Colors.deepOrange;
          } else if (type == 1) {
            typeStr = "Word";
            textColor = Colors.blue;
          } else if (type == 2) {
            typeStr = "Excel";
            textColor = Colors.green;
          } else if (type == 3) {
            typeStr = "视频";
            textColor = Colors.black;
          } else if (type == 4) {
            typeStr = "PDF";
            textColor = Colors.black;
          } else if (type == 5) {
            typeStr = "txt";
            textColor = Colors.black;
          } else if (type == 6) {
            typeStr = "图片";
            textColor = Colors.black;
          } else {
            typeStr = "其他";
            textColor = Colors.grey;
          }
          return Container(
            child: InkWell(
              onTap: () {
                NavigatorUtils.pushPage(
                  context,
                  StudyDataDatilsPage(
                    id: item.id,
                  ),
                );
                if (item.videoUrl != null && item.videoUrl.length > 0) {
                  // NavigatorUtils.pushPage(
                  //   context,
                  //   PdfWidgetPage(
                  //     showTitle: true,
                  //     title: item.videoName,
                  //     url: item.videoUrl,
                  //     isPdf: type == 4,
                  //   ),
                  // );
                } else {
                  ToastUtils.showToast("资料暂不可查看详情");
                }
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                      color: Colors.white,
                      padding: EdgeInsets.only(left: 12, top: 12, right: 12),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text(
                                      item.videoName,
                                      style: TextStyle(
                                          fontSize: 14, color: Colors.black),
                                    ),
                                    SizedBox(
                                      height: 8,
                                    ),
                                    Text(
                                      "${item.createTime}",
                                      style: TextStyle(
                                          fontSize: 12, color: Colors.black),
                                    )
                                  ],
                                ),
                              ),
                              Text(
                                "$typeStr",
                                style: TextStyle(
                                    color: textColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.w600),
                              ),
                              SizedBox(
                                width: 8,
                              ),
                              type < 7
                                  ? Icon(
                                      Icons.arrow_forward_ios,
                                      size: 16,
                                    )
                                  : SizedBox(),
                            ],
                          ),
                          Container(
                            width: double.infinity,
                            height: 1,
                            color: Color(0xffeeeeee),
                            margin: EdgeInsets.only(top: 10),
                          )
                        ],
                      ))
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

///ListView 自定义滑动监听回调
class CustomScrollDelegate extends SliverChildBuilderDelegate {
  //定义滑动回调监听
  Function(int firstIndex, int lastIndex) scrollCallBack;

  //构造函数
  CustomScrollDelegate(builder, {int itemCount, this.scrollCallBack})
      : super(builder, childCount: itemCount);

  @override
  double estimateMaxScrollOffset(int firstIndex, int lastIndex,
      double leadingScrollOffset, double trailingScrollOffset) {
    if (scrollCallBack != null) {
      scrollCallBack(firstIndex, lastIndex);
    }
    return super.estimateMaxScrollOffset(
        firstIndex, lastIndex, leadingScrollOffset, trailingScrollOffset);
  }
}
